package org.lex.swing.widgets.console;

import java.awt.LayoutManager;
import java.io.Writer;

import javax.swing.JPanel;
import javax.swing.event.EventListenerList;

import org.lex.utils.SystemProperties;

public abstract class AbstractSwingConsole extends JPanel implements IGUIConsole {
	private static final String nl = SystemProperties.lineSeparator();
	private EventListenerList listenerList = null;

	public AbstractSwingConsole(LayoutManager layout) {
		super(layout);
		this.listenerList = new EventListenerList();
	}

	public abstract AbstractSwingConsole print(Object o);

	public Writer getErr() {
		return null;
	}

	public Writer getOut() {
		return null;
	}

	public AbstractSwingConsole println() {
		return this.print(nl);
	}

	public AbstractSwingConsole println(Object o) {
		return this.print(o).println();
	}

	public void addConsoleListener(ConsoleListener l) {
		this.listenerList.add(ConsoleListener.class, l);
	}

	public void removeConsoleListener(ConsoleListener l) {
		this.listenerList.remove(ConsoleListener.class, l);
	}

	protected void fireConsoleExecute(String command) {
		// Guaranteed to return a non-null array
		Object[] listeners = listenerList.getListenerList();
		// Process the listeners last to first, notifying
		// those that are interested in this event
		for (int i = listeners.length - 2; i >= 0; i -= 2)
			if (listeners[i] == ConsoleListener.class)
				((ConsoleListener) listeners[i + 1]).execute(command);
	}
}
